package com.woniuxy.intellihome.controller.admin;


import com.baomidou.mybatisplus.extension.api.R;
import com.woniuxy.intellihome.entity.Category;
import com.woniuxy.intellihome.entity.ResponseEntity;
import com.woniuxy.intellihome.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Hw 0812 11:49 增加category的add,list方法
 * @since 2021-08-11
 */
@RestController
@Slf4j
@RequestMapping("/admin/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("test")
    public String test(){
        return "ok";
    }

    @RequestMapping("add")
    public ResponseEntity add(@RequestBody Category category){
        List<Category> categoryList = categoryService.list();
        //根据已有的sort得出最大的sortNum
        int sortMax=0;
        for (Category category1 : categoryList) {
            if(category1.getSort()>=sortMax){
                sortMax=category1.getSort()+1;
            }
        }
        category.setSort(sortMax);
        try {
        categoryService.save(category);
        }catch (Exception e){
            e.printStackTrace();
            return  new ResponseEntity(403,"增加种类失败");
        }
        ResponseEntity<Category> entity = new ResponseEntity<>(200, "ok");
        entity.setData(category);
        return  entity;
    }
    //上下架
    @RequestMapping("upDown")
    public ResponseEntity add(int id){
        Category category = categoryService.getById(id);
        if("y".equals( category.getStatus())){
            category.setStatus("n");
        }else{
            category.setStatus("y");
        }
        categoryService.updateById(category);
        ResponseEntity<Category> entity = new ResponseEntity<>(200,"成功上下架");
        entity.setData(category);
        return  entity;
    }

    @RequestMapping("update")
    public ResponseEntity update(@RequestBody Category category){
        categoryService.updateById(category);
        ResponseEntity<Object> entity = new ResponseEntity<>(200, "ok");
        entity.setData(category);
        return entity;

    }

    @RequestMapping("list")
    public ResponseEntity<List<Category>> list(){
        List<Category> categoryList = categoryService.list();
        ResponseEntity responseEntity = ResponseEntity.SUCCESS;
        responseEntity.setData(categoryList);
        return responseEntity;
    }


}

